// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// G [author] rhyme_lph
// m [email]  rhymelph@gmail.com
// b [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/chat_room_message_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/button/notification_button.dart';
import 'package:finance_app/src/widgets/chat_room/left_chat_item.dart';
import 'package:finance_app/src/widgets/chat_room/right_chat_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/pop/icon_follow_menu.dart';
import 'package:finance_app/src/widgets/speech_bottom_widget.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/ace_virtual_assistant/chat_room_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:finance_app/generated/a.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

@RouterMeta(paramName: "chatRoomPage")
class ChatRoomPage extends StatefulWidget {
  final String entryPoint;

  const ChatRoomPage({Key key, this.entryPoint}) : super(key: key);

  @override
  _ChatRoomPageState createState() => _ChatRoomPageState();
}

class _ChatRoomPageState extends State<ChatRoomPage>
    with PagePresenter<ChatRoomPage, ChatRoomProvider> {
  @override
  void initState() {
    provider.entryPoint = widget.entryPoint;
    super.initState();
  }

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<String>(
            selector: (_, __) => __.data?.name ?? '',
            builder: (BuildContext context, String value, Widget child) =>
                Text(S.current.ace_virtual_assistant),
          ),
          actions: [
            GlobalNotificationButton(),
          ]);

  @override
  Widget get buildWidget => ColoredBox(
        color: Color.fromRGBO(249, 249, 249, 1),
        child: Stack(
          children: [
            listBuilder<bool>(
                selector: (_, __) => __.isShowVoice,
                builder: (BuildContext context, bool value, Widget child) =>
                    Container(
                      height: MediaQuery.of(context).size.height,
                      width: MediaQuery.of(context).size.width,
                      margin: EdgeInsets.only(
                          bottom: getDp(62) +
                              (value == true ? provider.keyboardHeight : 0.0)),
                      child: child,
                    ),
                child: listBuilder<int>(
                  selector: (_, __) => __.chatGroups.length,
                  builder: (BuildContext context, int value, Widget child) =>
                      SmartRefresher(
                    onRefresh: provider.onLoadMore,
                    header: ClassicHeader(
                      idleText: S.current.pull_down_load_more,
                      releaseText: S.current.release_to_load_more,
                      refreshingText: S.current.loading,
                      completeText: S.current.loading_complete,
                    ),
                    controller: provider.refreshController,
                    child: ListView.builder(
                      controller: provider.scrollController,
                      padding: EdgeInsets.only(
                        bottom: 8.0,
                        left: isTablet(context)
                            ? mediaQuerySize(context).width * 0.02
                            : 0,
                        right: isTablet(context)
                            ? mediaQuerySize(context).width * 0.02
                            : 0,
                      ),
                      itemBuilder: _buildItems,
                      itemCount: value,
                    ),
                  ),
                )),
            listBuilder<int>(
              selector: (_, __) => __.suggestList.length,
              builder: (BuildContext context, int value, Widget child) =>
                  value > 0
                      ? Container(
                          color: aceWhiteGreyColor.withOpacity(0.9),
                          height: MediaQuery.of(context).size.height,
                          width: MediaQuery.of(context).size.width,
                          margin: EdgeInsets.only(bottom: getDp(62)),
                          child: ListView.builder(
                            itemBuilder: _buildSuggestItem,
                            reverse: true,
                            itemCount: value,
                          ),
                        )
                      : Container(),
            ),
            AnimatedPositioned(
              duration: Duration(milliseconds: 200),
              left: 0,
              right: 0,
              bottom: 0,
              child: listBuilder<bool>(
                selector: (_, __) => __.isShowVoice,
                builder: (BuildContext context, bool value, Widget child) =>
                    Column(
                  children: [
                    _buildInputBox(),
                    if (value == true)
                      SizedBox(
                          height: provider.keyboardHeight,
                          child: SpeechBottomWidget(
                            controller: provider.inputController,
                            onSend: () => provider.onSend(),
                          )),
                  ],
                ),
                child: _buildInputBox(),
              ),
            ),
          ],
        ),
      );

  Widget _buildInputBox() => Container(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                top: BorderSide(
              color: aceWhiteGreyColor,
              width: getDp(6),
            ))),
        height: getDp(62),
        alignment: Alignment.centerLeft,
        child: Row(
          children: [
            IconFollowMenu(
              onSelect: provider.onSelectAddFile,
              padding: EdgeInsets.symmetric(
                horizontal: getDp(25),
                vertical: getDp(22),
              ),
              child: SvgPicture.asset(
                A.assetsImagesStyleBlueAdd,
                width: getDp(18),
                height: getDp(18),
                fit: BoxFit.contain,
              ),
            ),
            Expanded(
              child: listBuilder<bool>(
                  selector: (_, __) => __.isShowVoice,
                  builder: (BuildContext context, bool value, Widget child) {
                    Widget child = TextFormField(
                      autofocus: true,
                      enabled: !value,
                      controller: provider.inputController,
                      focusNode: provider.inputFocusNode,
                      textInputAction: TextInputAction.send,
                      onEditingComplete: provider.onSend,
                      decoration: InputDecoration(
                          border: InputBorder.none,
                          fillColor: Colors.white,
                          contentPadding: EdgeInsets.only(
                              bottom: getDp(20), top: getDp(14)),
                          filled: true,
                          hintText: S.current.type_your_message_here,
                          hintStyle: TextStyle(
                            color: aceDarkGrayColor70,
                            fontSize: getSp(16),
                            fontWeight: FontWeight.w400,
                            height: 22 / 16,
                          )),
                    );
                    if (value == true) {
                      child = GestureDetector(
                        onTap: provider.onVoice,
                        child: child,
                      );
                    }
                    return child;
                  }),
            ),
            PressedOpacityButton(
              onPressed: provider.onVoice,
              padding: EdgeInsets.symmetric(
                horizontal: getDp(25),
                vertical: getDp(21),
              ),
              child: listBuilder<bool>(
                selector: (_, __) => __.isShowVoice,
                builder: (BuildContext context, bool value, Widget child) =>
                    SvgPicture.asset(
                  value == true
                      ? A.assetsImagesStyleKeyboard
                      : A.assetsImagesStyleVoice,
                  width: getDp(18),
                  height: getDp(20),
                  fit: BoxFit.contain,
                ),
              ),
            ),
          ],
        ),
      );

  Widget _buildItems(BuildContext context, int index) {
    return listBuilder<ChatRoomMessageGroupEntity>(
      selector: (_, __) => __.chatGroups[index],
      builder: (BuildContext context, ChatRoomMessageGroupEntity value,
          Widget child) {
        if (value.userId != Config.userProfile?.id) {
          return LeftChatItem(
            avatar: provider.data.members
                .firstWhere((element) => element.id == value.userId)
                .avatar,
            contents: value.messages,
            time: DateTimeUtils.formatDateTimeChatRoom(value.createdAt),
            onAction: (action) {
              provider.onActionTo(
                action['type'],
                action['text'],
                action['data'],
              );
            },
          );
        }
        return RightChatItem(
          contents: value.messages,
          time: DateTimeUtils.formatDateTimeChatRoom(value.createdAt),
        );
      },
    );
  }

  Widget _buildSuggestItem(BuildContext context, int index) {
    final data = provider.suggestList[index];
    return PressedOpacityButton(
      padding: EdgeInsets.symmetric(
        horizontal: getDp(25),
        vertical: getDp(10),
      ),
      border: Border(
          top: BorderSide(
        color: aceGrayColor,
      )),
      onPressed: () {
        provider.onEnterSuggest(data);
      },
      child: Text(
        data.question,
        style: TextStyle(
          color: aceBlackColor,
          fontSize: getSp(16),
          fontWeight: FontWeight.w400,
          height: 22 / 16,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
    );
  }
}
